/** 后台登录 **/
import localStorage from '@/common/js/store.js'
import Util from '@/common/js/util.js'
import { getToken, setToken, removeToken } from '@/common/js/auth.js'
const loginState = localStorage.get('user_info', {})

export default {
  namespaced: true,
  state: {
    token: getToken(),
    user_name: Util.getDefValue(loginState.user_name, false),
    mhm_id: Util.getDefValue(loginState.mhm_id, 1)
  },
  mutations: {
    LOGIN(state, provider) {
      state.user_name = provider.user_name
      state.mhm_id = provider.mhm_id
      const token = provider.auth_token.ak + ':' + provider.auth_token.sk
      state.token = token;
      // 储存用户信息
      localStorage.set('user_info', state)
      // 储存token
      setToken(token);
    },
    LOGOUT(state) {
      state.token = undefined;
      localStorage.clear()
      removeToken();
    }
  },
  getters: {
    isLogin(state) {
      return !!state.token;
    },
    token(state) {
      const token = state.token;
      if (token) {
        const authToken = token.split(':');
        return {
          ak: authToken[0],
          sk: authToken[1]
        }
      } else {
        return {
          ak: '',
          sk: ''
        }
      }
    },
    userName(state) {
      return state.user_name ? state.user_name : ''
    },
    // 当前机构
    mhmId(state) {
      return state.mhm_id ? state.mhm_id : 1
    }
  },
  actions: {
    setLogin({ commit }, data) {
      commit('LOGIN', data)
    },
    setLogout({ commit }) {
      commit('LOGOUT')
    }
  }
}
